package com.hyy.cmppserver.netway.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.drondea.sms.channel.ChannelSession;
import com.drondea.sms.common.util.MsgId;
import com.drondea.sms.message.IMessage;
import com.drondea.sms.message.cmpp.CmppDeliverRequestMessage;
import com.drondea.sms.message.cmpp.CmppReportRequestMessage;
import com.drondea.sms.session.cmpp.CmppServerSession;
import com.drondea.sms.thirdparty.SmsDcs;
import com.drondea.sms.type.GlobalConstants;
import com.drondea.sms.type.UserChannelConfig;
import com.hyy.api.domain.sms.cmpp2.InboxLog;
import com.hyy.api.domain.sms.cmpp2.InputLog;
import com.hyy.api.domain.sms.cmpp2.ReportLog;
import com.hyy.api.domain.sms.cmpp2.ReportNotify;
import com.hyy.api.util.SMSUtil;
import com.hyy.cmppserver.netway.handler.ReportResponseCustomHandler;
import com.hyy.cmppserver.netway.service.ITcpService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
public class CmppAPIServiceImpl implements ITcpService {

//    @Resource
//    private ProducerService producerService;
    /**
     * 生成存储下游msgId本地缓存的key
     * @param bachNum
     * @return
     */
    @Override
    public String genLocalCacheKey(String bachNum, String account) {
        return "cmpp2_" + bachNum + "_" + account;
    }

    @Override
    public IMessage getReportMessage(ChannelSession channelSession, ReportLog reportLog) {

        // 写入状态
        CmppDeliverRequestMessage request = new CmppDeliverRequestMessage();
        request.setMsgId(new MsgId());
        request.getHeader().setSequenceId(channelSession.getSequenceNumber().next());
        String phoneNo = reportLog.getPhoneNo().replaceFirst("\\+", "");

        request.setSrcTerminalId(phoneNo);
        CmppReportRequestMessage reportRequestMessage = new CmppReportRequestMessage();
        reportRequestMessage.setDestterminalId(phoneNo);
        String msgId = reportLog.getCrMsgId();
        if (StringUtils.isBlank(msgId)) {
            log.error("report msgId is null, {}", reportLog);
            return null;
        }
        List<String> list = Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
        for (int i = 0; i < msgId.length(); i++) {
            String c = msgId.charAt(i) + "";
            if (!list.contains(c)) {
                log.info("error--msgId-----{}", msgId);
            }

        }
        reportRequestMessage.setMsgId(new MsgId(msgId));
        reportRequestMessage.setSubmitTime(reportLog.getSubmitTime());
        reportRequestMessage.setDoneTime(reportLog.getDoneTime());
        reportRequestMessage.setStat(reportLog.getStat());

        reportRequestMessage.setSmscSequence(0);
        request.setReportRequestMessage(reportRequestMessage);
        request.setRegisteredDelivery((short) 1);

        ReportNotify reportNotify = new ReportNotify();
        reportNotify.setId(reportLog.getId());
        reportNotify.setYmd(reportLog.getYmd());

        Integer needProviderDest = reportLog.getNeedProviderDest();
        if (needProviderDest != null && needProviderDest == 1) {
            String destId = reportLog.getDestId() == null ? GlobalConstants.EMPTY_STRING : reportLog.getDestId();
            request.setDestId(destId);
            request.setReserved("1");
        }
        request.setMessageResponseHandler(new ReportResponseCustomHandler(reportNotify));

        return request;
    }

    @Override
    public IMessage getMOMessage(ChannelSession channelSession, InboxLog inboxLog) {
        // 写入上行
        CmppDeliverRequestMessage request = new CmppDeliverRequestMessage();
        request.setMsgId(new MsgId());
        request.getHeader().setSequenceId(channelSession.getSequenceNumber().next());
        if (StringUtils.isNotBlank(inboxLog.getCharset())) {
            request.setMsgContent(inboxLog.getContent(), new SmsDcs(SMSUtil.getGeneralDataCodingDcs(inboxLog.getCharset())));
        } else {
            request.setMsgContent(inboxLog.getContent());
        }

//        String phoneNo = inbox.getPhone_No().replaceFirst("\\+", "");
//        //过滤前的手机号
//        phoneNo = DatabaseCache.getUserCountryCodePhoneNo(inbox.getEnterprise_User_Id(),phoneNo);
        request.setSrcTerminalId(inboxLog.getPhoneNo());

        UserChannelConfig channelConfig = ((CmppServerSession) channelSession).getUserChannelConfig();
//        EnterpriseUser enterpriseUser = DatabaseCache.getEnterpriseUserCachedById(Integer.parseInt(channelConfig.getId()));
//        if (enterpriseUser == null) {
//            inbox.setNotify_Status_Code(NotifyStatus.FAIL.toString());
//            return null;
//        }
        // TODO: 2023/1/5
        request.setDestId(inboxLog.getCusSpNumber());

//        ReportNotify reportNotify =  SMSUtil.buildReportNotify(inbox);
//        request.setMessageResponseHandler(new AbstractMOResponseHandler(reportNotify, this) {
//            @Override
//            public void setResponseInfo(ReportNotify reportNotify, IMessage msgRequest, IMessage msgResponse) {
//                CmppDeliverResponseMessage responseMsg = (CmppDeliverResponseMessage) msgResponse;
//                reportNotify.setNotify_Response_Status("MO:" + responseMsg.getResult());
//            }
//
//            @Override
//            public void setRequestInfo(ReportNotify reportNotify, IMessage msgRequest) {
//                CmppDeliverRequestMessage requestMsg = (CmppDeliverRequestMessage) msgRequest;
//                String content = requestMsg.getMsgContent();
//                reportNotify.setContent(content);
//                reportNotify.setContent_Length(content.length());
//            }
//        });

        return request;
    }

    @Override
    public int saveInput(InputLog inputLog) {

        //提交队列
        String s = JSONObject.toJSONString(inputLog);
        log.debug("inputLog,{}", s);
//        producerService.sendMessage(s);

        return 0;
    }

}
